package com.shun.service

import com.shun.commons.ApiUtils
import com.shun.commons.exception.ApiException
import com.shun.entity.Company
import com.shun.entity.Dispatch
import com.shun.entity.Machine
import com.shun.entity.User
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.stereotype.Service
import java.util.*

/**
 * Created by Administrator on 2017/8/13.
 */
@Service
class DispatchService {

    @Autowired
    private lateinit var mongoTemplate: MongoTemplate

    @Autowired
    private lateinit var utils: ApiUtils

    fun create(params: Map<String, Any>, user: User) {
        val tempCompany = mongoTemplate.findOne(Query.query(Criteria("name").`is`(params["name"])), Company::class.java) ?: throw ApiException("名称为${params["name"]}商户信息不存在")

        val tempUseUser = mongoTemplate.findOne(Query.query(Criteria("username").`is`(params["useUser"])), User::class.java) ?: throw ApiException("用户名为${params["useUser"]}的用户信息不存在")

        val tempInstallUser = mongoTemplate.findOne(Query.query(Criteria("username").`is`(params["installUser"])), User::class.java) ?: throw ApiException("用户名为${params["useUser"]}的用户信息不存在")

        val tempSignUser = mongoTemplate.findOne(Query.query(Criteria("username").`is`(params["signUser"])), User::class.java) ?: throw ApiException("用户名为${params["useUser"]}的用户信息不存在")

        val tempMachine = mongoTemplate.findOne(Query.query(Criteria("machineCode").`is`(params["machineCode"])), Machine::class.java) ?: throw ApiException("设备编码为${params["machineCode"]}的设备信息不存在")

        val dispatch = Dispatch()

        dispatch.company = tempCompany
        dispatch.installUser = tempInstallUser
        dispatch.useUser = tempUseUser
        dispatch.signUser = tempSignUser
        dispatch.money = params["money"].toString().toDouble()
        dispatch.remark = params["remark"] as String
        dispatch.machineTools = params["machineTools"] as String
        dispatch.machine = tempMachine
        dispatch.searchKey = build(dispatch)
        dispatch.createTime = Date()
        dispatch.time = params["time"] as String
        dispatch.type = params["type"] as String
        dispatch.messageMoney = params["messageMoney"].toString().toDouble()
        dispatch.moneyType = params["moneyType"].toString()
        if (params["installUser"].toString().isNullOrBlank()) {
            dispatch.status = 0
        } else dispatch.status = 1

        mongoTemplate.insert(dispatch)
    }

    fun list(params: Map<String, Any?>): Any {
        val criteria = Criteria()

        if (params["searchKey"].toString().isNotBlank()) criteria.and("searchKey").regex(params["searchKey"].toString())

        if (params["status"].toString().isNotBlank()) criteria.and("status").`in`(params["status"].toString().split(",").map(String::toInt))
        val query = Query.query(criteria)

        val page = if (params["page"] != null) params["page"].toString().toInt() else 0
        val size = if (params["size"] != null) params["size"].toString().toInt() else 10


        if (page > 0) {
            query.skip((page - 1) * size).limit(size)
        }

        val list = mongoTemplate.find(query, Dispatch::class.java)

        return if (page > 0) {
            mapOf(
                    "list" to list,
                    "page" to page,
                    "size" to size,
                    "total" to mongoTemplate.count(query, Dispatch::class.java)
            )
        } else {
            list
        }
    }


    fun build(t: Dispatch): String? {
        val keys = getSearchKeys(t)
        t.searchKey = if (keys.isNotEmpty()) {
            val first = utils.stringToPinyin(keys[0]!!, "first")
            val full = utils.stringToPinyin(keys[0]!!, "full")
            arrayOf(first.first(), first, full, *keys).distinct().joinToString(",")
        } else {
            ""
        }
        return t.searchKey
    }

    fun getSearchKeys(t: Dispatch) = arrayOf(t.company!!.name, t.installUser!!.username)
}